/**
 * @filename:SysActionServiceImpl 2022年1月27日
 * @project Wonder wallet Framework  V1.0
 * Copyright(c) 2018 LuZhongren Co. Ltd. 
 * All right reserved. 
 */
package com.wonder.admin.service.impl;

import com.wonder.admin.domain.SysAction;
import com.wonder.admin.domain.SysField;
import com.wonder.admin.domain.SysMenu;
import com.wonder.admin.mapper.SysActionDao;
import com.wonder.admin.service.SysActionService;
import com.wonder.admin.service.SysFieldService;
import com.wonder.admin.service.SysMenuService;
import com.wonder.admin.request.SysActionRequest;
import com.wonder.common.utils.MessageUtils;
import com.wonder.common.utils.StringUtils;


import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;


/**   
 * @Description:TODO(模块方法管理服务实现)
 *
 * @version: V1.0
 * @author: LuZhongren
 * 
 */
@Service
public class SysActionServiceImpl  extends ServiceImpl<SysActionDao, SysAction> implements SysActionService  {

	@Autowired
	private SysMenuService sysMenuService;
	
	@Autowired
	private SysFieldService sysFieldService;
	
   /**
     * 修改模块方法管理信息
     * 
     * @param SysAction信息
     * @return 结果
     */
    @Override
    public int updateEx(SysAction sysAction){
       if(sysAction!=null)
		     return this.baseMapper.updateById(sysAction);
       return 0;
    }
    
    
    /**
	 * Description:模块方法管理分页返回
	 * @request:检索条件
	 * @page：分页参数
	 * @return:分页记录
	 */
	@Override 
	public IPage<SysAction> selectList(SysActionRequest request, Page<SysAction> page){
	    LambdaQueryWrapper<SysAction> lambdaQueryWrapper = new LambdaQueryWrapper<>();
               
	    if (null != request.getMenu_id()) {
	       lambdaQueryWrapper.eq(SysAction::getMenu_id, request.getMenu_id());
	      }               
        
		lambdaQueryWrapper.orderByAsc(SysAction::getSortid);	
		Page<SysAction> selectPage = this.baseMapper.selectPage(page, lambdaQueryWrapper);

		return selectPage;
    }
	
	
	/**
	 * 获取JOIN列表参数
	 * @param actionList
	 * @return
	 */
	@Override
	public List<Map<String, Object>> getExtend(List<SysAction> actionList) {
		
		List<Map<String, Object>> withJoinList=new ArrayList<Map<String,Object>>();
		List<Integer> types=Arrays.asList(2, 3, 5,11);
	
		for(SysAction action:actionList) {
			if(StringUtils.hasText(action.getWith_join_table()) && types.contains(action.getType())){
				@SuppressWarnings("unchecked")
				List<Map<String, Object>> with_join_items = JSON.parseObject(action.getWith_join_table(),
						new ArrayList<Map<String, Object>>().getClass());
				if(with_join_items!=null && with_join_items.size()>0) {
					for(Map<String, Object> with_join:with_join_items) {
						with_join.put("action_type", action.getType());
						with_join.put("fields", getExtendFields(with_join));
						withJoinList.add(with_join);					
					}
				}
				
			}
		}
		
		return withJoinList;
		
//		$with_join = [];
//		foreach($actionList as $v){
//			if($v['with_join'] && in_array($v['type'],[2,3,5,11])){
//				foreach(json_decode($v['with_join'],true) as $n){
//					$n['action_type'] = $v['type'];
//					$n['fields'] = $this->getExtendFields($n);
//					array_push($with_join, $n);
//				}
//			}
//		}
//
//		return $with_join;
		
	}
	

	private List<Map<String,Object> >getExtendFields(Map<String, Object> map) {
		SysMenu sysMenu=sysMenuService.getOne(new QueryWrapper<SysMenu>().eq("controller_name", map.get("relative_table")));
		List<Map<String,Object>> fieldList=sysFieldService.listMaps(new QueryWrapper<SysField>().eq("menu_id", sysMenu.getMenu_id()).orderByAsc("sortid"));
		List<String> joinFields=new ArrayList<String>();
		
		if(map.get("fields")!=null) {
			joinFields=StringUtils.castList(map.get("fields"), String.class);
			
//			Object obj=map.get("fields");
//			if (obj.getClass().isArray()) {
//			    int length = Array.getLength(obj);
//			    for (int i = 0; i < length; i++) {
//			    	joinFields.add( Array.get(obj, i).toString());
//			    }
//			}
		}
		
		List<Map<String, Object>> removeList=new ArrayList<Map<String,Object>>();
		
		for(Map<String,Object> v:fieldList) {
			v.put("belong_table", map.get("relative_table").toString());
			v.put("table_name", sysMenu.getTable_name());
			
			if(!joinFields.contains(v.get("field").toString())) removeList.add(v) ;    // fieldList.remove(v);
			
		
		}
		fieldList.removeAll(removeList);
		
		return fieldList;
	}
	
	/**
	 * 
	 * @param entity
	 * @return
	 */
	@Override
	public String validate(SysAction entity) {
		Integer type=entity.getType();
		if(type==null) return MessageUtils.message("action.type.required");
		if(type==6 ||  type==8 || type==9 || type==13)//Reset password,
		{
			if(entity.getFields()==null || entity.getFields().length==0) {
				return MessageUtils.message("action.select.fields");
			}else {
				if(entity.getFields().length >1) {
					return MessageUtils.message("action.select.one.field");
				}
			}
			
		}else if (type==7) {//设置状态
			if(entity.getFields()==null || entity.getFields().length==0) {
				return MessageUtils.message("action.select.fields");
			}
			if(!StringUtils.hasText(entity.getStatus_val())){
				return MessageUtils.message("action.status.value.required");
			}			
			
		}else if(type==15 || type==16) {
			if(!StringUtils.hasText(entity.getJump())){
				return MessageUtils.message("action.jump.value.required");
			}		
			
		}else if(type==51){
			
			
		}
		
		return null;
	}
	
//	private function getExtendFields($val){
//		$menuInfo = Menu::field('menu_id,table_name')->where('controller_name',$val['relative_table'])->find();
//		$fieldList = Field::where('menu_id',$menuInfo['menu_id'])->order('sortid asc')->select()->toArray();
//		foreach($fieldList as $k=>$v){
//			$fieldList[$k]['belong_table'] = $val['relative_table'];
//			$fieldList[$k]['table_name'] = $menuInfo['table_name'];
//			if(!in_array($v['field'],$val['fields'])){
//				unset($fieldList[$k]);
//			}
//		}
//		return $fieldList;
//	}
	
}